<template>
	<div class="quillWrapper">
		<div ref="quillContainer" :id="id">
      <el-button type="text">保存</el-button>
    </div>
	</div>
</template>
<script>
	import Quill from 'quill'
	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.core.css'
	import 'quill/dist/quill.snow.css'

	var defaultToolbar = [
		['bold', 'italic', 'underline', 'strike'],
		['blockquote', 'code-block', 'image'],
		[{ 'list': 'ordered'}, { 'list': 'bullet' }],
		[{ 'indent': '-1'}, { 'indent': '+1' }],
		[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
		[{ 'color': [] }, { 'background': [] }],
		[{ 'font': [] }],
		[{ 'align': [] }],
		['clean']
	]

	export default {
		name: 'vue-editor',
		props: {
			value: String,
			id: {
				type: String,
				default: 'quill-container'
			},
			placeholder: String,
			disabled: Boolean,
			editorToolbar: Array,
		},

		data() {
			return {
				quill: null,
				editor: null,
				toolbar: this.editorToolbar ? this.editorToolbar : defaultToolbar
			}
		},

		mounted() {
			this.initializeVue2Editor()
			this.handleUpdatedEditor()
		},

		watch: {
			value (val) {
				if (val !=  this.editor.innerHTML && !this.quill.hasFocus()) {
					this.editor.innerHTML = val
				}
			},
			disabled(status) {
				this.quill.enable(!status);
			}
		},

		methods: {
			initializeVue2Editor() {
				this.setQuillElement()
				this.setEditorElement()
				this.checkForInitialContent()
				this.setImagePasteSupport()
			},

			setQuillElement() {
				this.quill = new Quill(this.$refs.quillContainer, {
					modules: {
						toolbar: this.toolbar
					},
					placeholder: this.placeholder ? this.placeholder : '',
					theme: 'snow',
					readOnly: this.disabled ? this.disabled : false,
				})
			},

			setEditorElement() {
				this.editor = document.querySelector(`#${this.id} .ql-editor`)
			},

			checkForInitialContent() {
				this.editor.innerHTML = this.value || ''
			},
			setImagePasteSupport(){
				this.quill.root.addEventListener('drop', this.handleDrop.bind(this), false);
				this.quill.root.addEventListener('paste', this.handlePaste.bind(this), false);
			},

			handleDrop(evt) {
				evt.preventDefault();
				if (evt.dataTransfer && evt.dataTransfer.files && evt.dataTransfer.files.length) {
					this.readFiles(evt.dataTransfer.files, this.insert.bind(this));
				}
			},

			handlePaste(evt) {
				if (evt.clipboardData && evt.clipboardData.items && evt.clipboardData.items.length) {
					this.readFiles(evt.clipboardData.items, dataUrl => {
						const selection = this.quill.getSelection();
						if (selection) {
							// we must be in a browser that supports pasting (like Firefox)
							// so it has already been placed into the editor
						}
						else {
							// otherwise we wait until after the paste when this.quill.getSelection()
							// will return a valid index
							setTimeout(() => this.insert(dataUrl), 0);
						}
					});
				}
			},

			insert(dataUrl) {
				const index = (this.quill.getSelection() || {}).index || this.quill.getLength();
				this.quill.insertEmbed(index, 'image', dataUrl, 'user');
			},

			readFiles(files, callback) {
				// check each file for an image
				[].forEach.call(files, file => {
					if (!file.type.match(/^image\/(gif|jpe?g|a?png|svg|webp|bmp|vnd\.microsoft\.icon)/i)) {
						// file is not an image
						// Note that some file formats such as psd start with image/* but are not readable
						return;
					}
					// set up file reader
					const reader = new FileReader();
					reader.onload = (evt) => {
						callback(evt.target.result);
					};
					// read the clipboard item or file
					const blob = file.getAsFile ? file.getAsFile() : file;
					if (blob instanceof Blob) {
						reader.readAsDataURL(blob);
					}
				});
			},
			handleUpdatedEditor() {
				this.quill.on('text-change', () => {
					this.$emit('input', this.editor.innerHTML)
				})
			}
		}
	}
</script>

<style>
	#quill-container {
		height: 200px;
	}
</style>
